<?php
/**
 * Copyright 2011  SURFfoundation
 * 
 * This file is part of ESCAPE.
 * 
 * ESCAPE is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * ESCAPE is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with ESCAPE.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * For more information:
 * http://escapesurf.wordpress.com/
 * http://www.surffoundation.nl/
 * 
 * Contact: d.vierkant@utwente.nl
 * 
 * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3
 */
?>
<?php
/**
 * Controller
 * 
 * Base class for MVC controllers.
 */
abstract class mvc_Controller
{
	/**
	 * @var string View implementation class name, to be overridden in a sub class
	 */
	protected $viewImplementationClassName = null;

	/**
	 * @var string Path to where the action classes can be found, should end with a '/', to be overridden in a sub class
	 */
	protected $actionPath = null;

	/**
	 * @var string Package prefix for action classes, to be overridden in a sub class
	 */
	protected $actionPackage = null;
	
	
	/**
	 * @var array Request attributes
	 */
	protected $requestAttributes = null;

	/**
	 * Constructor.
	 * @param array $requestAttributes Request attributes.
	 */
	public function __construct(&$requestAttributes)
	{
		$this->requestAttributes = &$requestAttributes;
	}

	/**
	 * Process a request using an action.
	 * @param string $actionName Action name
	 */
	public function processRequest($actionName = null)
	{
		$actionName = ucfirst($actionName);
		
		$this->requestAttributes['actionName'] = $actionName;
		
		$this->preProcessRequest();

		$actionName = $this->requestAttributes['actionName'];
		
		$action = null;
		$viewName = null;
		$finishedActions = false;
		while($finishedActions == false)
		{
			$action = $this->getAction($actionName, $this->requestAttributes);
			
			if($action === null)
			{
				$action = $this->onActionNotFound($actionName);
			}

			if($action === null)
			{
				$finishedActions = true;
			}
			else
			{
				$viewName = $action->startHandleRequest();
				
				if(strpos($viewName, "action::") === 0)
				{
					$actionName = substr($viewName, strlen("action::"));
				}
				else
				{
					$finishedActions = true;
				}
			}
		}
		
		if($viewName !== null && $viewName !== false)
		{
			$view = $this->getView($viewName, $this->requestAttributes);
			if($view === null)
			{
				$view = $this->onViewNotFound($viewName);
			}

			if($view !== null)
			{
				$view->displayView($viewName, $this->requestAttributes);
			}
		}
		
		$this->postProcessRequest();
	}

	public function preProcessRequest()
	{
	}
	
	public function postProcessRequest()
	{
	}
	
	/**
	 * Get an instance of an action by name. 
	 * @param string $actionName Name of the action
	 * @return mvc_Action Action
	 */
	protected function getAction($actionName)
	{
		$action = null;
		
		// check action name, to prevent exploits 
		if(preg_match('/^\w+$/', $actionName))
		{
			$actionFileName = $this->actionPath . $actionName . '.php';
			$actionClassName = $this->actionPackage . '_' . $actionName;

			// don't show warnings (from non-existing actions)
			$previousErrorLevel = error_reporting(E_ALL ^ E_WARNING);
			include_once($actionFileName);
			error_reporting($previousErrorLevel);

			if(class_exists($actionClassName))
			{
				$action = new $actionClassName($this->requestAttributes);
				if(get_class($action) !== $actionClassName)
				{
					// specified class name and actual class name are not identical, possibly due to case mismatch
					$action = null;
				}
			}
		}
		
		return $action;
	}
	
	/**
	 * Get an instance of a view by name. 
	 * @param string $actionName Name of the action
	 * @return mvc_Action Action
	 */
	protected function getView($viewName)
	{
		$view = null;
		
		// check view name, to prevent exploits 
		if(preg_match('/^\w+$/', $viewName))
		{
			$view = new $this->viewImplementationClassName($this->requestAttributes);
		}
		
		return $view;
	}
	
	/**
	 * Action not found handler.
	 * @param $actionName Current action name
	 * @return mvc_Action Replacement action or null
	 */
	protected function onActionNotFound($actionName)
	{
		header("HTTP/1.0 404 Not Found");
		print 'ERROR: Action "' . htmlspecialchars($actionName) . '" not found!';
		
		return null;
	}

	/**
	 * View not found handler.
	 * @param $viewName Current view name
	 * @return mvc_View Replacement view or null
	 */
	protected function onViewNotFound($viewName)
	{
		header("HTTP/1.0 500 Internal Server Error");
		print 'ERROR: View "' . htmlspecialchars($viewName) . '" not found!';

		return null;
	}
}